package com.xinrui.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinrui.sunnyday.dao.SetmealDao;
import com.xinrui.sunnyday.entity.QueryPageBean;
import com.xinrui.sunnyday.exception.SunnydayException;
import com.xinrui.sunnyday.pojo.Setmeal;
import com.xinrui.sunnyday.service.SetmealService;
import com.xinrui.sunnyday.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Override
    public PageInfo<Setmeal> findPage(QueryPageBean queryPageBean) {
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
        }
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<Setmeal> list = setmealDao.findPage(queryPageBean.getQueryString());
        return new PageInfo<>(list);
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkGroupIds) throws SunnydayException {
        if (null == checkGroupIds) {
            throw new SunnydayException("所选检查组不能为空！");
        }
        setmealDao.add(setmeal);
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealId", setmeal.getId());
        map.put("checkGroupIds", checkGroupIds);
        setmealDao.addSetmealAndCheckGroup(map);

        generateMobileStaticHtml();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> findSetmealAndCheckGroupById(Integer id) {
        return setmealDao.findSetmealAndCheckGroupById(id);
    }

    @Override
    public void update(Setmeal setmeal, Integer[] ids) throws SunnydayException {
        if (null == ids) {
            throw new SunnydayException("所选检查组不能为空！");
        }
        setmealDao.update(setmeal);
        setmealDao.deleteSetmealAndCheckGroupById(setmeal.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealId", setmeal.getId());
        map.put("checkGroupIds", ids);
        setmealDao.addSetmealAndCheckGroup(map);

        generateMobileStaticHtml();
    }

    @Override
    public void deleteById(Integer id) throws SunnydayException {
        int count = setmealDao.findOrderBySetmealId(id);
        if (count > 0) {
            throw new SunnydayException("该套餐已被订单所关联！");
        }
        setmealDao.deleteSetmealAndCheckGroupById(id);
        setmealDao.deleteById(id);
    }

    @Override
    public List<String> findImgs() {
        return setmealDao.findImgs();
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findDetailById(Integer id) {
        return setmealDao.findDetailById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }


    //==============================移动端静态化页面==================================
    @Autowired
    private FreeMarkerConfig freeMarkerConfig; //注入FreeMarker配置类
    @Value("${out_put_path}")
    private String out_put_path; //引入FreeMarker配置类中的输出路径

    /**
     * 封装生成静态页面的方法
     */
    private void generateHtml(String templateName, Map<String, Object> dataMap, String outFileName) {
        //1.获取FreeMarker配置类
        Configuration configuration = freeMarkerConfig.getConfiguration();
        BufferedWriter bw = null;
        try {
            //2.加载模板文件  -->已有，参数传进来
            Template template = configuration.getTemplate(templateName);
            //3.构建数据     -->已有，参数传进来
            //4.输出文件路径  -->文件名称已有，参数传进来
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName), "utf-8"));
            //5.将数据填充到模板
            template.process(dataMap, bw);
            //6.刷新缓冲流
            bw.flush();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void generateMobileStaticHtml() {
        try {
            generateSetmealListHtml();
            generateSetmealDetailHtml();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void generateSetmealListHtml() {
        String templateName = "mobile_setmeal.ftl";
        List<Setmeal> setmealList = setmealDao.findAll();
        setmealList.forEach(setmeal -> {
            setmeal.setImg(QiNiuUtils.DOMAIN + setmeal.getImg());
        });
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList", setmealList);
        String setmealListFile = out_put_path + "mobile_setmeal.html";
        generateHtml(templateName, dataMap, setmealListFile);
    }

    private void generateSetmealDetailHtml() {
        //1.准备模板文件路径,freemarker配置文件中已经配置好了路径前缀
        String templateName = "mobile_setmeal_detail.ftl";
        //2.准备数据：把所有套餐都生成详情页面,方便测试
        List<Setmeal> setmealList = setmealDao.findAll();
        //2.1setmealList中的套餐是没有详情信息，即没有检查组也没有检查项的信息，要查询一遍
        for (Setmeal setmeal : setmealList) {
            //2.2.获取套餐详情
            Setmeal setmealDetail = setmealDao.findDetailById(setmeal.getId());
            //2.3设置套餐的图片路径
            setmealDetail.setImg(QiNiuUtils.DOMAIN + setmealDetail.getImg());
            //3.构建数据
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal", setmealDetail);
            //4.输出全路径
            String setmealListFile = out_put_path + "mobile_setmeal_" + setmealDetail.getId() + ".html";
            //调用封装的页面生成方法
            generateHtml(templateName, dataMap, setmealListFile);
        }
    }
}
